package com.fortune.rainshine.system.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fortune.rainshine.common.BaseController;
import com.fortune.rainshine.common.JsonResult;
import com.fortune.rainshine.common.PageResult;
import com.fortune.rainshine.common.exception.ParameterException;
import com.fortune.rainshine.common.shiro.EndecryptUtil;
import com.fortune.rainshine.common.utils.StringUtil;
import com.fortune.rainshine.system.service.RoleService;
import com.fortune.rainshine.system.service.UserService;
import com.fortune.rainshinecommon.model.system.Role;
import com.fortune.rainshinecommon.model.system.User;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequiresPermissions("user:view")
    @RequestMapping
    public String user(Model model) {
		List<Role> roles = roleService.list(false);
		model.addAttribute("roles", roles);
		// 获取用户权限
		Set<String> authorities = getLoginUserAuthorities();
		// 获取登录用户的按钮展示情况
		model.addAttribute("add", authorities.contains("user:add"));
		model.addAttribute("edit", authorities.contains("user:edit"));
		model.addAttribute("delete", authorities.contains("user:delete"));
		model.addAttribute("updatePsw", authorities.contains("user:updatePsw"));
		
		return "system/user.html";
    }

    @RequestMapping("/editForm")
    public String addUser(Model model,String shopId,String edit) {
    	//List<Role> roles = roleService.list(false);
    	User user = this.getLoginUser();
    	List<Role> role = roleService.getByUserId(user.getUserId());
		int roleId = role.get(0).getRoleId();
		boolean overstep = false;
		//判断若为店长，则自动生成店员账号，限制为五个
		out:if(roleId == 5 ) {
			List<User> users = userService.getShopAssistant(user.getUserId(),shopId,true);
			if(users.size() >= 5 && edit.equals("0")) {
				overstep = true;
				break out;
			}
			if(users.size() == 0 && edit.equals("0")) {
				model.addAttribute("userName", user.getUsername()+shopId+"001");
			}
			if(users.size() > 0 && users.size() < 5 && edit.equals("0")) {
				List<User> userAll = userService.getShopAssistant(user.getUserId(),shopId,false);
				List<Integer> exampleNames = new ArrayList<Integer>();
				DecimalFormat df = new DecimalFormat("000");
				for(User item : userAll){
					int length = item.getUsername().length();
					String number = item.getUsername().substring(length-3, length);
					
					
					int j = Integer.parseInt(number);
					
					exampleNames.add(j);
				}
				
				int name = Collections.max(exampleNames)+1;
				model.addAttribute("userName", user.getUsername()+shopId+df.format(name));
			}
		}
		
        List<Role> roles = roleService.listAdminShow();
		model.addAttribute("edit",Integer.parseInt(edit));
        model.addAttribute("overstep", overstep);
        model.addAttribute("roleId", roleId);
        model.addAttribute("roles", roles);
        return "system/user_form.html";
    }

    /**
     * 查询用户列表
     */
    @RequiresPermissions("user:view")
    @ResponseBody
    @RequestMapping("/list")
    public PageResult<User> list(Integer page, Integer limit, String username, String phone,Integer shopId) {
        if (page == null) {
            page = 0;
            limit = 0;
        }
        //获取当前登录用户
        User user =this.getLoginUser();
        user.setShopId(shopId);
        return userService.list(page, limit, true, username, phone,user);
    }

    /**
     * 添加用户
     **/
    @RequiresPermissions("user:add")
    @ResponseBody
    @RequestMapping("/add")
    public JsonResult add(User user, String roleId) {
    	user.setCreateId(getLoginUser().getUserId());
    	user.setUpdateId(getLoginUser().getUserId());
        user.setRoles(getRoles(roleId));
        user.setPassword("123456");
        if (userService.add(user,getLoginUser().getUserId())) {
            return JsonResult.ok("添加成功");
        } else {
            return JsonResult.error("添加失败");
        }
    }

    /**
     * 修改用户
     **/
    @RequiresPermissions("user:edit")
    @ResponseBody
    @RequestMapping("/update")
    public JsonResult update(User user, String roleId) {
    	user.setUpdateId(getLoginUser().getUserId());
//    	if(StringUtils.isNotBlank(roleId)){
//            user.setRoles(getRoles(roleId));
//        }
        if (userService.update(user)) {
            return JsonResult.ok("修改成功");
        } else {
            return JsonResult.error("修改失败");
        }
    }

    private List<Role> getRoles(String roleStr) {
        List<Role> roles = new ArrayList<>();
        String[] split = roleStr.split(",");
        for (String t : split) {
            if (t.equals("1")) {
                throw new ParameterException("不能添加超级管理员");
            }
            roles.add(new Role(Integer.parseInt(t)));
        }
        return roles;
    }

    /**
     * 修改用户状态
     **/
    @RequiresPermissions("user:delete")
    @ResponseBody
    @RequestMapping("/updateState")
    public JsonResult updateState(Integer userId, Integer state) {
        if (userService.updateState(userId, state)) {
            return JsonResult.ok();
        } else {
            return JsonResult.error();
        }
    }

    /**
     * 修改自己密码
     **/
    @RequiresPermissions("user:updatePsw")
    @ResponseBody
    @RequestMapping("/updatePsw")
    public JsonResult updatePsw(String oldPsw, String newPsw) {
        if ("admin".equals(getLoginUser().getUsername())) {
            return JsonResult.error("演示帐号admin关闭该功能");
        }
        String finalSecret = EndecryptUtil.encrytMd5(oldPsw, getLoginUserName(), 3);
        if (!finalSecret.equals(getLoginUser().getPassword())) {
            return JsonResult.error("原密码输入不正确");
        }
        if (userService.updatePsw(getLoginUserId(), getLoginUserName(), newPsw)) {
            return JsonResult.ok("修改成功");
        } else {
            return JsonResult.error("修改失败");
        }
    }

    /**
     * 重置密码
     **/
    @RequiresPermissions("user:edit")
    @ResponseBody
    @RequestMapping("/restPsw")
    public JsonResult resetPsw(Integer userId) {
        User byId = userService.getById(userId);
        if (userService.updatePsw(userId, byId.getUsername(), "123456")) {
            return JsonResult.ok("重置成功");
        } else {
            return JsonResult.error("重置失败");
        }
    }
}
